package com.sniper.web.shiro.session.redis;

import com.sniper.web.redis.RedisConnUtil;
import com.sniper.web.shiro.session.cache.CacheFactory;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.cache.CacheManager;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class RedisCacheManager implements CacheManager {

    // fast lookup by name map
    private final ConcurrentMap<String, CacheFactory> caches = new ConcurrentHashMap<>();

    /**
     * The Redis key prefix for the sessions
     */
    private String keyPrefix = "shiro_redis_session:";

    private RedisConnUtil redisConn;

    private long ttlTime = 1800000L;


    public void setRedisConn(RedisConnUtil redisConn) {
        this.redisConn = redisConn;
    }

    public void setTtlTime(long ttlTime) {
        this.ttlTime = ttlTime;
    }

    /**
     * Returns the Redis session keys prefix.
     *
     * @return The prefix
     */
    public String getKeyPrefix() {
        return keyPrefix;
    }

    /**
     * Sets the Redis sessions key prefix.
     *
     * @param keyPrefix The prefix
     */
    public void setKeyPrefix(String keyPrefix) {
        this.keyPrefix = keyPrefix;
    }

    @Override
    public <K, V> CacheFactory<K, V> getCache(String name) throws CacheException {

        // 这里可以扩展其他缓存处理器
        // create a new cache instance
        // add it to the cache collection
        return caches.computeIfAbsent(name, k -> new RedisCache<K, V>(redisConn, ttlTime, keyPrefix));
    }
}